package com.blb.socket.demo4;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;

/**
 * BIO服务器
 */
public class BIOServer {

    public static final int PORT = 8888;

    public static void main(String[] args) {
        //创建ServerSocket对象
        try (ServerSocket serverSocket = new ServerSocket(PORT);){
            while(true){
                //接收客户端
                Socket client = serverSocket.accept();
                //对客户端执行IO操作
                new Thread(() -> {
                    handleClient(client);
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 处理客户端
     * @param client
     */
    private static void handleClient(Socket client){
        System.out.println("客户端连接了：" + client.getInetAddress()+"，线程：" + Thread.currentThread().getName());
        //获得IO流
        try(ObjectInputStream in = new ObjectInputStream(client.getInputStream());
            ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());){
            //读取客户端的数据
            String msg = in.readUTF();
            System.out.println(client.getInetAddress()+"客户端的消息：" + msg);
            //发送数据给客户端
            out.writeUTF("Hello 我是服务器，当前时间：" + LocalDateTime.now());
            out.flush();
        }catch (IOException ex){
            ex.printStackTrace();
        }
    }
}
